package com.cmdi.mq.demo1;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * @Description: 消费消息BROADCASTING
 * @Author: gaozb
 */
public class ConsumerBroadcast {
    public static void main(String[] args) throws Exception {
        //指定消费者组，如果没有consumer-group需要首先创建
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer-group2");
        // 设置NameServer的地址
        consumer.setNamesrvAddr("10.254.243.246:9876;10.254.243.249:9876");
        // 设置从哪读取，失效？
        //consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        // 订阅的topic，可将*换成tag名
        consumer.subscribe("topic1","*");
        /**
         * 默认负载均衡CLUSTERING模式
         * CLUSTERING模式消费：同一个消费者组中多个消费者共同消费队列消息，每个消费者处理的消息不同
         * BROADCASTING模式消费：所有的消费者（不管是否同一个消费者组）消费的消息都是相同的
         **/
        consumer.setMessageModel(MessageModel.BROADCASTING);
        //设置消费监听
        consumer.registerMessageListener(new MessageListenerConcurrently() {

            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                            ConsumeConcurrentlyContext context) {
                //拿到一批消息
                System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
                //返回确认信号
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //启动消费
        consumer.start();
        System.out.printf("Consumer Started.%n");
    }
}